import wtforms
from flask_wtf.file import FileAllowed
from wtforms.validators import Email, Length, EqualTo, InputRequired
from models import UserModel, EmailCaptchaModel


# from exts import db


class RegisterForm(wtforms.Form):
    email = wtforms.StringField(validators=[Email(message='邮箱格式错误')])
    captcha = wtforms.StringField(validators=[Length(min=4, max=4, message='验证码格式错误')])
    username = wtforms.StringField(validators=[Length(min=3, max=200, message='用户名格式错误')])
    password = wtforms.StringField(validators=[Length(min=6, max=20, message='密码格式错误')])
    password_confirm = wtforms.StringField(validators=[EqualTo('password', message='两次输入的密码不一致')])

    def validate_email(self, field):
        email = field.data
        user = UserModel.query.filter_by(email=email).first()
        if user:
            raise wtforms.ValidationError(message='该邮箱已被注册')

    def validate_username(self, field):
        username = field.data
        user = UserModel.query.filter_by(username=username).first()
        if user:
            raise wtforms.ValidationError(message='该用户名已存在')

    def validate_captcha(self, field):
        captcha = field.data
        email = self.email.data
        captcha_model = EmailCaptchaModel.query.filter_by(email=email, captcha=captcha).first()
        if not captcha_model:
            raise wtforms.ValidationError(message='邮箱验证码错误')


class LoginForm(wtforms.Form):
    email = wtforms.StringField(validators=[Email(message='邮箱格式错误')])
    password = wtforms.StringField(validators=[Length(min=6, max=20, message='密码格式错误')])


class QuestionForm(wtforms.Form):
    title = wtforms.StringField(validators=[Length(min=1, max=50, message='标题格式错误，太短或太长')])
    content = wtforms.StringField(validators=[Length(min=3, message='内容格式错误，太短或过长')])
    price = wtforms.StringField(validators=[Length(min=0, max=10, message='价格格式错误')])


class AnswerForm(wtforms.Form):
    content = wtforms.StringField(validators=[Length(min=1, message='内容太短')])
    question_id = wtforms.IntegerField(validators=[InputRequired(message='必须输入问题id')])


class ChatForm(wtforms.Form):
    content = wtforms.StringField(validators=[Length(min=0, message='内容太短')])
